package com.car.rental.user.filter;

import com.car.rental.common.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import java.io.IOException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import org.springframework.lang.NonNull;

@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(
        @NonNull HttpServletRequest request,
        @NonNull HttpServletResponse response,
        @NonNull FilterChain filterChain
    ) throws ServletException, IOException {
        log.info("进入JWT过滤器，请求路径: {}", request.getRequestURI());
        String token = request.getHeader("Authorization");
        log.info("获取到的token: {}", token);
        
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            log.info("截取后的token: {}", token);
            
            try {
                if (jwtUtils.validateToken(token)) {
                    String username = jwtUtils.getUsernameFromToken(token);
                    Long userId = jwtUtils.getUserIdFromToken(token);
                    log.info("token验证成功，用户ID: {}, 用户名: {}", userId, username);
                    UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(userId, null, Collections.emptyList());
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    log.info("成功设置认证信息到SecurityContext");
                }
            } catch (Exception e) {
                log.error("token验证失败: {}, token内容: {}", e.getMessage(), token, e);
                SecurityContextHolder.clearContext();
                log.info("已清除SecurityContext");
            }
        } else {
            log.warn("未找到token或token格式不正确");
        }
        
        filterChain.doFilter(request, response);
    }
} 